package v1

import (
	"net/http"
	"strconv"

	"zhihu-api/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 创建评论请求
type CreateCommentRequest struct {
	Content string `json:"content" binding:"required"`
}

// 创建问题评论
func CreateQuestionComment(c *gin.Context) {
	questionID := c.Param("id")
	userID := c.MustGet("userID").(uint)

	var req CreateCommentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查问题是否存在
	var question models.Question
	if err := models.DB.First(&question, questionID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "问题不存在"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取问题失败"})
		return
	}

	// 创建评论
	comment := models.Comment{
		Content:       req.Content,
		CommentatorID: userID,
		ResourceType:  "question",
		ResourceID:    question.ID,
	}

	if err := models.DB.Create(&comment).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建评论失败"})
		return
	}

	// 返回创建的评论(包含用户信息)
	if err := models.DB.Preload("Commentator").First(&comment, comment.ID).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论详情失败"})
		return
	}

	c.JSON(http.StatusCreated, comment)
}

// 创建答案评论
func CreateAnswerComment(c *gin.Context) {
	answerID := c.Param("id")
	userID := c.MustGet("userID").(uint)

	var req CreateCommentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查答案是否存在
	var answer models.Answer
	if err := models.DB.First(&answer, answerID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "答案不存在"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取答案失败"})
		return
	}

	// 创建评论
	comment := models.Comment{
		Content:       req.Content,
		CommentatorID: userID,
		ResourceType:  "answer",
		ResourceID:    answer.ID,
	}

	tx := models.DB.Begin()

	if err := tx.Create(&comment).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建评论失败"})
		return
	}

	// 更新答案评论数
	if err := tx.Model(&answer).Update("comment_count", gorm.Expr("comment_count + ?", 1)).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新答案评论数失败"})
		return
	}

	tx.Commit()

	// 返回创建的评论(包含用户信息)
	if err := models.DB.Preload("Commentator").First(&comment, comment.ID).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论详情失败"})
		return
	}

	c.JSON(http.StatusCreated, comment)
}

// 更新评论
func UpdateComment(c *gin.Context) {
	commentID := c.Param("id")
	userID := c.MustGet("userID").(uint)

	var req CreateCommentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查评论是否存在
	var comment models.Comment
	if err := models.DB.First(&comment, commentID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "评论不存在"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论失败"})
		return
	}

	// 检查权限
	if comment.CommentatorID != userID {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限更新此评论"})
		return
	}

	// 更新评论
	if err := models.DB.Model(&comment).Update("content", req.Content).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新评论失败"})
		return
	}

	// 返回更新后的评论
	if err := models.DB.Preload("Commentator").First(&comment, commentID).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取更新后的评论失败"})
		return
	}

	c.JSON(http.StatusOK, comment)
}

// 删除评论
func DeleteComment(c *gin.Context) {
	commentID := c.Param("id")
	userID := c.MustGet("userID").(uint)

	// 检查评论是否存在
	var comment models.Comment
	if err := models.DB.First(&comment, commentID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "评论不存在"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论失败"})
		return
	}

	// 检查权限
	if comment.CommentatorID != userID {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限删除此评论"})
		return
	}

	tx := models.DB.Begin()

	// 删除评论
	if err := tx.Delete(&comment).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除评论失败"})
		return
	}

	// 如果是答案评论，更新答案评论数
	if comment.ResourceType == "answer" {
		if err := tx.Model(&models.Answer{}).Where("id = ?", comment.ResourceID).
			Update("comment_count", gorm.Expr("comment_count - ?", 1)).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": "更新答案评论数失败"})
			return
		}
	}

	tx.Commit()
	c.JSON(http.StatusOK, gin.H{"message": "评论删除成功"})
}

// 创建评论回复请求
type CreateCommentReplyRequest struct {
	Content   string `json:"content" binding:"required"`
	ReplyToID uint   `json:"replyToId"`
}

// 创建评论回复
func CreateCommentReply(c *gin.Context) {
	commentID := c.Param("id")
	userID := c.MustGet("userID").(uint)
	idUint, _ := strconv.ParseUint(commentID, 10, 32)

	var req CreateCommentReplyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查根评论是否存在
	var rootComment models.Comment
	if err := models.DB.First(&rootComment, commentID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "评论不存在"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论失败"})
		return
	}

	// 如果提供了replyToId，验证回复的评论是否存在
	if req.ReplyToID != 0 {
		var replyTo models.Comment
		if err := models.DB.First(&replyTo, req.ReplyToID).Error; err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "回复的评论不存在"})
			return
		}

		// 确保回复的评论属于同一个根评论
		if replyTo.RootCommentID != nil && *replyTo.RootCommentID != uint(idUint) && replyTo.ID != uint(idUint) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "回复的评论不属于同一个根评论"})
			return
		}
	}

	// 创建回复评论
	rootCommentID := uint(idUint)
	comment := models.Comment{
		Content:       req.Content,
		CommentatorID: userID,
		ResourceType:  rootComment.ResourceType,
		ResourceID:    rootComment.ResourceID,
		RootCommentID: &rootCommentID,
	}

	if req.ReplyToID != 0 {
		comment.ReplyToID = &req.ReplyToID
	}

	tx := models.DB.Begin()

	if err := tx.Create(&comment).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建评论回复失败"})
		return
	}

	// 如果是答案评论，更新答案评论数
	if rootComment.ResourceType == "answer" {
		if err := tx.Model(&models.Answer{}).Where("id = ?", rootComment.ResourceID).
			Update("comment_count", gorm.Expr("comment_count + ?", 1)).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": "更新答案评论数失败"})
			return
		}
	}

	tx.Commit()

	// 返回创建的评论(包含用户信息)
	if err := models.DB.Preload("Commentator").First(&comment, comment.ID).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论详情失败"})
		return
	}

	c.JSON(http.StatusCreated, comment)
}
